import BasicConfigurationAlertModal from '@/pages/complaintsReport/manager/components/BasicConfigurationAlertModal';
import DetailModal from '@/pages/complaintsReport/manager/components/DetailModal';
import { getBasicSettingsByUserId } from '@/services/backend/basicSettingsController';
import { getComplaintInfo } from '@/services/backend/complaintInfoController';
import { export1 } from '@/services/backend/exportController';
import { uploadFile } from '@/services/custom/importController';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { useModel } from '@umijs/max';
import { Button, Flex, message, notification, Space, Upload } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 基础配置提示的弹窗
   *  */
  const [basicConfigurationAlertModalVisible, setBasicConfigurationAlertModalVisible] =
    useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution detail window
   * @zh-CN row详情窗口的弹窗
   * */
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.ComplaintInfoVo>();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  /**
   * 是否完成基础配置
   */
  const isCompleteBasicConfiguration = async () => {
    // console.log(currentUser);
    try {
      //发送请求,进行判断
      const res = await getBasicSettingsByUserId({
        //@ts-ignore
        userId: currentUser.id,
      });
      //完成,返回true;未完成,返回false
      if (res.code === 200 && res?.data?.caseFiling && res?.data?.name && res?.data?.code && res?.data?.contactsList
        && res?.data?.notRegisteredDesc && res?.data?.notRegisteredTerm && res?.data?.registeredTerm) {
        return true;
      } else {
        return false;
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  /**
   * 处理基础配置的弹窗
   */
  const handleBasicConfigurationModal = async () => {
    setCreateModalVisible(true);
    //判断系统的基础配置是否完成
    const success = await isCompleteBasicConfiguration();
    //未完成,弹窗提示跳转到基础配置页面
    if (!success) {
      setBasicConfigurationAlertModalVisible(true);
    } else {
      //完成,弹窗新增页面
      setCreateModalVisible(true);
    }
  };

  //首次加载弹窗提醒
  useEffect(() => {
    const loadData = async () => {
      const success = await isCompleteBasicConfiguration();
      if (!success) {
        setBasicConfigurationAlertModalVisible(true);
      }
    };

    loadData();
  }, []);

  const sourceEnumMap = new Map([
    ['投诉、举报', '投诉、举报'],
    ['其他部门移送', '其他部门移送'],
    ['上级交办', '上级交办'],
  ]);
  const acceptanceEnumMap = new Map([
    [0, '不予受理'],
    [1, '已受理'],
  ]);
  const registerEnumMap = new Map([
    [0, '不予立案'],
    [1, '已立案'],
  ]);

  const columns: ProColumns<API.ComplaintInfoVo>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'index',
      hideInForm: true,
    },
    {
      title: '登记号',
      dataIndex: 'registrationNo',
      valueType: 'text',
    },
    {
      title: '投诉举报人',
      dataIndex: 'complainant',
      valueType: 'text',
    },
    {
      title: '当事人',
      dataIndex: 'agent',
      valueType: 'text',
    },
    {
      title: '投诉争议事实',
      dataIndex: 'complaintDesc',
      valueType: 'text',
      width: 400,
    },
    {
      title: '来源分类',
      dataIndex: 'source',
      valueEnum: sourceEnumMap,
    },
    {
      title: '受理状态',
      dataIndex: 'isAcceptance',
      valueEnum: acceptanceEnumMap,
    },
    {
      title: '受理日期',
      dataIndex: 'acceptanceDate',
      valueType: 'date',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '调解终止日期',
      dataIndex: 'mediateDate',
      valueType: 'date',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '立案状态',
      dataIndex: 'isRegister',
      valueEnum: registerEnumMap,
    },
    {
      title: '立案处理日期',
      dataIndex: 'filingHandlingDate',
      valueType: 'date',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '投诉接收日期',
      sorter: true,
      dataIndex: 'complaintDate',
      valueType: 'date',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '投诉接收日期',
      sorter: true,
      dataIndex: 'complaintDateList',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
    },
    {
      title: '数据更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '数据更新时间',
      sorter: true,
      dataIndex: 'updateTimeList',
      valueType: 'dateTimeRange',
      hideInForm: true,
      hideInTable: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size={'middle'}>
          <Flex justify={'space-evenly'} gap="7px" wrap>
            <Button
              size={'small'}
              variant="outlined"
              onClick={() => {
                setDetailModalVisible(true);
                setCurrentRow(record);
              }}
            >
              详情
            </Button>
            <Button
              size={'small'}
              variant="outlined"
              onClick={() => {
                setUpdateModalVisible(true);
                setCurrentRow(record);
              }}
            >
              编辑
            </Button>
            <Button
              size={'small'}
              variant="solid"
              color={'blue'}
              onClick={async () => {
                await export1({
                  //@ts-ignore
                  complaintInfoId: record.id,
                });
                notification.success({
                  message: '导出',
                  description: '一键导出成功',
                });
              }}
            >
              一键导出
            </Button>
          </Flex>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.ComplaintInfoVo>
        headerTitle={
          <Flex gap={15}>
            <Button type="primary" key="primary" onClick={handleBasicConfigurationModal}>
              <PlusOutlined /> 投诉举报录入
            </Button>
            <Upload
              name={'file'}
              maxCount={1}
              showUploadList={false}
              beforeUpload={(file) => {
                // console.log(file.type);
                const isExcel =
                  file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                if (!isExcel) {
                  message.error(`${file.name} 并不是excel文件`);
                }
                return isExcel || Upload.LIST_IGNORE;
              }}
              customRequest={async (options) => {
                console.log(options.file);
                try {
                  const res = await uploadFile({
                    file: options.file,
                  });
                  if(res.code === 200){
                    message.success(`数据导入成功`);
                  }
                } catch (e: any) {
                  message.error(`${options.filename} 文件上传失败`);
                }
              }}
            >
              <Button type="primary" variant={'solid'} color={'green'} icon={<UploadOutlined />}>
                Excel表导入
              </Button>
            </Upload>
          </Flex>
        }
        actionRef={actionRef}
        pagination={{
          showSizeChanger: true,
          //@ts-ignore
          position: 'bottomLeft',
        }}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        scroll={{ x: 'max-content' }}
        //@ts-ignore
        request={async (params) => {
          const size = params.pageSize || 0;
          const current = params.current || 0;
          const { data, code } = await getComplaintInfo(
            {
              size,
              current,
            } as API.getComplaintInfoParams,
            //@ts-ignore
            {
              ...params,
            },
          );

          // console.log(data?.records);
          return {
            success: code === 200,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      {/*新增悬浮窗*/}
      <CreateModal
        modalVisible={createModalVisible}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      {/*基础配置提示悬浮窗*/}
      <BasicConfigurationAlertModal
        modalVisible={basicConfigurationAlertModalVisible}
        onSubmit={() => {
          setBasicConfigurationAlertModalVisible(false);
        }}
        onCancel={() => {
          setBasicConfigurationAlertModalVisible(false);
        }}
      />
      {/*更新悬浮窗*/}
      {/* 在 UpdateModal 组件中添加 fetchOnOpen 属性 */}
      <UpdateModal
        oldData={currentRow}
        modalVisible={updateModalVisible}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
        fetchOnOpen={true} // 添加这个属性，表示在Modal打开时获取数据
      />
      {/*详情悬浮窗*/}
      <DetailModal
        oldData={currentRow}
        modalVisible={detailModalVisible}
        onSubmit={() => {
          setDetailModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setDetailModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default TableList;
